
;
(function($, $$) {
    $.fn.dialog = function(options) {
        var self = this, args = Array.prototype.slice.call(arguments);
        args.push($$.Dialog);
        var result = $$.createWidgetByJQuery.apply(self, args);
        if (result.jqObj !== undefined && options !== "widget") {
            return self;
        }
        return result;
    };

    $$.Dialog = function(self, options) {
        if (!(this instanceof $$.Dialog)) {
            return new $$.Dialog(self, options);
        }
        var defaults = {

            dlgClass : $$.defaultBorder + " uiCornerAll " + $$.defaultBoxShadow,

            titleBarClass : $$.defaultGradientBG,

            position : null,

            zIndex : 1000,

            draggable : false,

            resizable : false,

            minStatusWidth : 250,

            modal : false,

            buttonSet : null,

            minHeight : 300,

            maxHeight : 700,

            minWidth : 400,

            maxWidth : 1000,



            active : true,

            minimize : true,

            closable : true,

            noTitleBar : false,

            titleIcon : null,

            title : null,

            controlButton : true,

            autoOpen : true,

            destroyOnClose : true,

            closeAnimate : "slideUp",

            openAnimate : "slideDown",



            beforeClose : null,

            close : null,

            beforeOpen : null,

            open : null,

            beforeMin : null,

            min : null,

            beforeResume : null,

            resume : null,

            dragStart : null,

            draging : null,

            dragStop : null,

            resizeStart : null,

            resizing : null,

            resizeStop : null,

            minStatusHeight : 0,

            originHeight : 0,

            originWidth : 0,

            originPosition : null,

            overflowStatus : null,

            controlButtonSetHTML : '<div class="uiDialogButtonSet"><div class="uiUserBtn uiMinBtn uiIcon uiMinButtonIcon"></div><div class="uiUserBtn uiCloseBtn uiIcon uiCloseButtonIcon"></div></div>',

            titleBarHTML : '<div class="uiTitleBar"><span class="uiTitle"></span></div>',

            contentHTML : '<div class="uiContent"></div>',

            resizeHTML :'<div class="uiResizable"></div>',

            selectList : null
        };
        var opts = $.extend(defaults, options);
        $$.Dialog.prototype.superClass.call(this, self, opts);
        this.init();
    };
    $$.inherit($$.Dialog, $$.Widget, {

        init : function() {
            var dialogObj = this;
            dialogObj.createWidget();
            initDialog(dialogObj, dialogObj.jqObj, dialogObj.opts);
            return dialogObj;
        },

        title : function(title) {
            var dialogObj = this, self = dialogObj.jqObj, opts = dialogObj.opts;
            var obj = $("> .uiTitleBar > .uiTitle", self);
            if (title === undefined) {
                return obj.text();
            }
            opts.title = title;
            obj.html(obj.html().replace(obj.text(), title));
            return dialogObj;
        },

        titleIcon : function(titleIcon) {
            var dialogObj = this, self = dialogObj.jqObj, opts = dialogObj.opts;
            if (titleIcon === undefined) {
                return opts.titleIcon;
            }
            if (opts.titleIcon === null) {
                $("> .uiTitleBar > .uiTitle", self).prepend('<span class="uiTitleIcon" />');
            }
            var obj = $("> .uiTitleBar > .uiTitle > .uiTitleIcon", self).removeClass(opts.titleIcon).addClass(titleIcon);
            opts.titleIcon = titleIcon;
            return dialogObj;
        },

        content : function(content) {
            var dialogObj = this, self = dialogObj.jqObj, opts = dialogObj.opts;
            var contentObj = self.children(".uiContent");
            if (content === undefined) {
                return contentObj;
            }
            contentObj.empty().append($(content));
            return dialogObj;
        }
    });

    function initDialog(dialogObj, self, opts) {
        var titleBarClass = opts.titleBarClass + " uiCornerAll";

        if (opts.title === null) {
            opts.title = self.attr("title") || "";
        }

        if (opts.draggable) {
            titleBarClass += (" uiDraggable");
        }

        var controlButton = null;
        if (opts.controlButton) {
            controlButton = $(opts.controlButtonSetHTML);
            if (!opts.minimize) {
                controlButton.children(".uiMinBtn").hide();
            }
            if (!opts.closable) {
                controlButton.children(".uiCloseBtn").hide();
            }
        }


        var content = self.children().addClass("uiContent");
        if (opts.noTitleBar) {
            self.addClass("uiDialog uiWidget " + opts.dlgClass);
        }
        else {
            var tileBar = $(opts.titleBarHTML).addClass(titleBarClass).append(controlButton).children(".uiTitle").html(opts.title).end();
            if (opts.titleIcon !== null) {
                tileBar.children(".uiTitle").prepend($('<span class="uiTitleIcon" />').addClass(opts.titleIcon));
            }
            self.addClass("uiDialog uiWidget " + opts.dlgClass).prepend(tileBar);
        }

        if (opts.position !== null) {
            self.css("z-index", opts.zIndex + 1).moveToPos(opts.position);
        }

        if (opts.modal) {
            var maskObj = $("<div />").addClass("uiMask").appendTo("body");
            if (opts.position === null) {
                self.css("z-index", opts.zIndex + 1).moveToPos({position : "center"});
            }
            if ($$.msie6) {
                opts.selectList = $("select:visible").filter(
                    function(i) {
                        if ($(this).css("visibility") !== "hidden") {
                            return true;
                        }
                        return false;
                    }).css("visibility", "hidden");
                maskObj.height($(document).height());
            }
        }

        if (opts.buttonSet !== null) {
            var buttonSetHTML = "<div>";
            for (var key in opts.buttonSet) {
                buttonSetHTML += ("<div>" + key + "</div>");
            }
            buttonSetHTML += "</div>";
            $(buttonSetHTML).buttonSet({
                click : function(target) {
                    if (opts.disabled) {
                        return false;
                    }
                    if (opts.buttonSet[target.text()].call(this) === false) {
                        return false;
                    }

                    dialogObj.close(self, opts, target);
                }
            }).appendTo(self);
        }

        if (opts.resizable) {
            self.append(opts.resizeHTML);
            if (self.css("position") === "static") {
                self.css("position", "relative");
            }
        }
        opts.minHeight = Math.min(self.height(), opts.minHeight);
        opts.minWidth = Math.min(self.width(), opts.minWidth);
        setContentHeight(self, opts);

        initEvent(dialogObj, self, opts);
        if (opts.disabled) {

        }
        if (!opts.autoOpen) {
            self.hide();
        }
    }


    function initEvent(dialogObj, self, opts) {
        var posStr = self.css("position");

        self.find("> .uiTitleBar > .uiDialogButtonSet > .uiUserBtn").bind("click.uiDialog", function(e) {
            if (opts.disabled) {
                return false;
            }
            var obj = $(this);
            var func = null;
            if (obj.hasClass("uiMinBtn")) {
                func = "min";
            }
            else
            if (obj.hasClass("uiResumeBtn")) {
                func = "resume";
            }
            else
            if (obj.hasClass("uiCloseBtn")) {
                func = "close";
            }
            if (func != null) {
                if (self.is(":animated")) {
                    return false;
                }
                dialogObj[func](self, opts, obj, e);
                return false;
            }
        });

        if (opts.draggable) {
            var dragStopFunction = function(mask, offset) {
                if (opts.disabled) {
                    return false;
                }
                if ($.isFunction(opts.dragStop)) {
                    if (opts.dragStop.call(self) ==false) {
                        return false;
                    }
                }
                self.offset(offset);
            };
            self.draggable({
                event : {start : opts.dragStart, doing : opts.draging,  stop : dragStopFunction}
            });
        }

        if (opts.resizable) {
            var resizeStopFunc = function(mask, width, height) {
                if (opts.disabled) {
                    return false;
                }
                if ($.isFunction(opts.resizeStop)) {
                    if (opts.resizeStop.call(self) === false) {
                        return false;
                    }
                }
                height = Math.min(Math.max(opts.minHeight, height), opts.maxHeight);
                width = Math.min(Math.max(opts.minWidth, width), opts.maxWidth);
                var otherItemHeightTotal = 0, content = self.width(width).height(height).children(".uiContent");
                self.children().each(function() {
                    var obj = $(this);
                    if (!obj.hasClass("uiContent") && !obj.hasClass("uiResizable")) {
                        otherItemHeightTotal += $(this).outerHeight(true);
                    }
                });
                var outerOffset = content.outerHeight(true) - content.height();
                content.height(height - otherItemHeightTotal - outerOffset);
            };
            self.resizable({
                event : {start : opts.resizeStart, doing : opts.resizing,  stop : resizeStopFunc},
                minHeight : opts.minHeight,
                maxHeight : opts.maxHeight,
                minWidth : opts.minWidth,
                maxWidth : opts.maxWidth
            });
        }

        if (posStr !== "static" && posStr !== "relative") {
            if (opts.active && opts.autoOpen) {
                $(".uiDialog").not(self).each(function() {
                    var obj = $(this);
                    if (obj.css("position") !== "static" && obj.css("position") !== "relative") {
                        obj.css("z-index", opts.zIndex).children(".uiTitleBar").addClass("uiInactive");
                    }
                });
            }
            self.bind("mousedown.uiDialog", function(e) {
                if (opts.disabled) {
                    return;
                }
                self.css("z-index", opts.zIndex + 1).children(".uiTitleBar").removeClass("uiInactive");
                self.siblings(".uiDialog").each(function() {
                    var obj = $(this);
                    if (obj.css("position") !== "static" && obj.css("position") !== "relative") {
                        obj.css("z-index", opts.zIndex).children(".uiTitleBar").addClass("uiInactive");
                    }
                });
                var target = $(e.target);
                if (target.hasClass("uiDraggable") || target.hasClass("uiResizable") || target.parent().hasClass("uiDraggable")) {
                    return false;
                }
            });
        }
    }


    function setContentHeight(self, opts) {
        var otherItemHeightTotal = 0, contentHeight = 0, outerOffset = 0, content = self.children(".uiContent");
        self.children().each(function() {
            var obj = $(this);
            if (!obj.hasClass("uiContent") && !obj.hasClass("uiResizable")) {
                otherItemHeightTotal += $(this).outerHeight(true);
            }
        });
        contentHeight = content.outerHeight(true);
        outerOffset = contentHeight - content.height();
        var imgList = self.find("img");
        if (imgList.length !== 0) {
            var imgTotal = imgList.length;
            var completeLoad = 0;
            imgList.each(function() {
                if (this.complete) {
                    completeLoad++;
                    if (completeLoad === imgTotal) {
                        content.height(self.height() - otherItemHeightTotal - outerOffset);
                    }
                }
                else {
                    $(this).load(function() {
                        completeLoad++;
                        if (completeLoad === imgTotal) {
                            content.height(self.height() - otherItemHeightTotal - outerOffset);
                        }
                    });
                }
            });
        }
        else {
            content.height(self.height() - otherItemHeightTotal - outerOffset);
        }
    }

})(jQuery, BASE);